//
//  SGLevelViewController.m
//  EatNumber
//
//  Created by zg.shao on 14/12/19.
//  Copyright (c) 2014年 kuwo.cn. All rights reserved.
//

#import "SGLevelViewController.h"
#import "SGGameViewController.h"
#import "SGEatNumber.h"
#import "UIView+Sizes.h"
#import "SGAppDelegate.h"
#import "SGCustomScrollView.h"

#define nPageCount 6
#define nRowCount  5
#define nColCount  5
#define ITEMTAG 124

@interface SGLevelViewController () <UIScrollViewDelegate>
{
    UILabel  *_titleLabel;  // Select Level
    
    UIButton *_returnBtn;   // 返回按钮
    UIPageControl *_pageControl;
    SGCustomScrollView *_theScrollView;
}

@end

@implementation SGLevelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGameViewCtrl:) name:RESTORE_GAME_NOTIFICATION object:nil];
    
    [self.view setBackgroundColor:COLOR_WITH_RGB(0xf28179)];
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateLevelInfo];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initSubViews {
    CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
    [self initLevelViewWithFrame:rect];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _theScrollView.top - 60, SCREEN_WIDTH, 60)];
    [_titleLabel setText:@"选择关卡"];
    [_titleLabel setFont:[UIFont systemFontOfSize:24]];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_titleLabel setTextColor:[UIColor whiteColor]];
    [self.view addSubview:_titleLabel];
}

- (void)initLevelViewWithFrame:(CGRect)frame {
    _theScrollView = [[SGCustomScrollView alloc] initWithFrame:frame];

    _pageControl = [[UIPageControl alloc] init];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [self.view addSubview:_pageControl];
    
    const CGFloat nSpaceWidth = 7;
    const CGFloat nLeftSpace = 10;
    const CGFloat nItemWidth = (frame.size.width - nLeftSpace*2 - nSpaceWidth * 4) / 5.0;
    
    _pageControl.numberOfPages = nPageCount;
    _pageControl.currentPage = [[SGEatNumber defaultEatNumber] playerWinLevelIndex]/25;
    [_pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    
    int index = 1;
    for (int t=0; t<nPageCount; t++) {
        for (int row = 0; row < nRowCount; row ++) {
            for (int col = 0; col < nColCount; col ++) {
                CGRect rect = CGRectMake(t*frame.size.width + nLeftSpace + col * (nItemWidth + nSpaceWidth), row * (nItemWidth + nSpaceWidth), nItemWidth, nItemWidth);
                UIButton *btnItem = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                [btnItem setFrame:rect];
                btnItem.tag = index + ITEMTAG;
                [btnItem setBackgroundColor:COLOR_WITH_RGB(0xdda840)];
                [btnItem setTitle:[NSString stringWithFormat:@"%d", index ++] forState:UIControlStateNormal];
                [btnItem.titleLabel setFont:[UIFont fontWithName:@"AvenirNextCondensed-Heavy" size:30]];
                [btnItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [btnItem addTarget:self action:@selector(levelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                
                UIImageView *imageView;
                if (index <= [[SGEatNumber defaultEatNumber] playerWinLevelIndex]) {
                    [btnItem setBackgroundColor:COLOR_WITH_RGB(0xdda840)];
                    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"level_pass"]];
                } else if (index > [[SGEatNumber defaultEatNumber] playerWinLevelIndex]+1){
                    [btnItem setBackgroundColor:COLOR_WITH_RGB(0x666666)];
                    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"level_lock"]];
                }

                [_theScrollView addSubview:btnItem];
            }
        }
    }
    
    _theScrollView.delegate = self;
    _theScrollView.center = self.view.center;
    [_theScrollView setContentSize:CGSizeMake(frame.size.width*nPageCount, frame.size.height)];
    [_theScrollView setPagingEnabled:YES];
    [_theScrollView setShowsHorizontalScrollIndicator:NO];
    [_theScrollView setContentOffset:CGPointMake(([[SGEatNumber defaultEatNumber] playerWinLevelIndex]/25)*SCREEN_WIDTH, 0)];
    [self.view addSubview:_theScrollView];
    
    [_pageControl setFrame:CGRectMake(_theScrollView.left, _theScrollView.bottom, _theScrollView.width, 15)];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    _pageControl.currentPage = scrollView.contentOffset.x/SCREEN_WIDTH;
}

- (void)updateLevelInfo {
    // 滚到 玩家上次玩的那一关 相关页
    [_theScrollView setContentOffset:CGPointMake(([[SGEatNumber defaultEatNumber] getCurLevel]/25)*SCREEN_WIDTH, 0)];
    
    int index = 1;
    for (int t=0; t<nPageCount; t++) {
        for (int row = 0; row < nRowCount; row ++) {
            for (int col = 0; col < nColCount; col ++) {
                UIButton *button = (UIButton *)[_theScrollView viewWithTag:index+ITEMTAG];
                if (button) {
                    UIView *view = [button viewWithTag:ITEMTAG];
                    if (view) {
                        [view removeFromSuperview];
                    }
                    UIImageView *imageView;
                    if (index <= [[SGEatNumber defaultEatNumber] playerWinLevelIndex]) {
                        [button setBackgroundColor:COLOR_WITH_RGB(0xdda840)];
                        imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"level_pass"]];
                    } else if (index > [[SGEatNumber defaultEatNumber] playerWinLevelIndex]+1){
                        [button setBackgroundColor:COLOR_WITH_RGB(0x666666)];
                        imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"level_lock"]];
                    } else {
                        [button setBackgroundColor:COLOR_WITH_RGB(0xdda840)];
                    }
                    
                    if (imageView) {
                        imageView.tag = ITEMTAG;
                        [imageView setFrame:CGRectMake(button.width-imageView.width-2, button.height-imageView.height-2, imageView.width, imageView.height)];
                        [button addSubview:imageView];
                    }
                }
                index ++;
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)returnBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)levelBtnClick:(UIButton*)sender {
    int levelIndex = (int)[sender.titleLabel.text integerValue];
    if (levelIndex <= [[SGEatNumber defaultEatNumber] playerWinLevelIndex]+1) {
        [[SGEatNumber defaultEatNumber] newGameWithLevel:levelIndex];
        [SGAppDelegate playGameDefaultSoundWithState:self.isMusicOn];
        
        [self showGameViewCtrl:nil];
    } else {
        UIAlertView *tipAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先解锁上一关！" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [tipAlertView show];
    }
}

- (void)showGameViewCtrl:(NSNotification *)aNotify {
    SGGameViewController *gameViewCtrl = [[SGGameViewController alloc] init];
    [self.navigationController pushViewController:gameViewCtrl animated:YES];
}

- (void)changePage:(id)sender {
    int page = _pageControl.currentPage;
    [_theScrollView setContentOffset:CGPointMake(page * SCREEN_WIDTH, 0)];
}
@end
